<template>
  <el-card class="w-full pt-[5px] pb0">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      label-width="68px"
      style="padding-left: 20px !important; padding-right: 20px !important"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="dutyStatus" class="ml-[-76px]">
            <el-radio-group
              v-model="queryParams.dutyStatus"
              @change="handleQuery"
            >
              <el-radio-button :label="'全部('+dutyStatusCount.all+')'" value="" />
              <el-radio-button
                v-for="dict in cfg_category_zzzt"
                :key="dict.value"
                :label="dict.label+'('+(dutyStatusCount[dict.value]?dutyStatusCount[dict.value].dutyStatusCount:0)+')'"
                :value="dict.value"
              ></el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="人员类型" prop="typeId">
            <el-select
              v-model="queryParams.typeId"
              placeholder="请选择人员类型"
              clearable
            >
              <el-option label="" value="" />
              <el-option
                v-for="dict in cfg_category_jgrylx"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="姓名" prop="name" label-width="40px">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入姓名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="所属单位" prop="unitName">
            <el-input
              v-model="queryParams.unitName"
              placeholder="请输入所属单位"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="学历" prop="eduLevelId" label-width="40px">
            <el-select
              v-model="queryParams.eduLevelId"
              placeholder="请选择学历"
              clearable
            >
              <el-option label="" value="" />
              <el-option
                v-for="dict in cfg_category_xl"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="岗位类型" prop="jobType">
            <el-select
              v-model="queryParams.jobType"
              placeholder="请选择岗位类型"
              clearable
            >
              <el-option label="" value="" />
              <el-option
                v-for="dict in cfg_category_gwlx"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card
    class="w-full mt-[20px]"
    style="padding-left: 20px !important; padding-right: 20px !important"
  >
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="getCurRole()!='biz_kyry'">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['research:person:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="getCurRole()!='biz_kyry'">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['research:person:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info" 
            plain 
            icon="back"
            @click="back(proxy)"
        >返回</el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="personList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="人员类型" align="center" prop="typeId">
        <template #default="scope">
          <dict-tag :options="cfg_category_jgrylx" :value="scope.row.typeId" :showSpan="true"/>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" >
        <template v-slot="scope">
        <div>
            <el-link type="primary" @click="handleView(scope.row)"> {{ scope.row.name }}  </el-link>
        </div>
        </template>  
      </el-table-column>
      <el-table-column label="所属单位" align="center" prop="unitName" />
      <el-table-column label="职称" align="center" prop="titleId">
        <template #default="scope">
          <dict-tag :options="cfg_category_zc" :value="scope.row.titleId" :showSpan="true"/>
        </template>
      </el-table-column>
      <el-table-column label="学历" align="center" prop="eduLevelId">
        <template #default="scope">
          <dict-tag :options="cfg_category_xl" :value="scope.row.eduLevelId" :showSpan="true"/>
        </template>
      </el-table-column>
      <el-table-column
        label="入职时间"
        align="center"
        prop="hireDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.hireDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="在职情况" align="center" prop="dutyStatus">
        <template #default="scope">
          <dict-tag
            :options="cfg_category_zzzt"
            :value="scope.row.dutyStatus"
            :showSpan="true"
          />
        </template>
      </el-table-column>
      <el-table-column label="岗位类型" align="center" prop="jobType">
        <template #default="scope">
          <dict-tag :options="cfg_category_gwlx" :value="scope.row.jobType" :showSpan="true"/>
        </template>
      </el-table-column>

      <el-table-column label="所属研究机构名称集合" align="center" prop="researchNameList" width="200"></el-table-column>

      <el-table-column v-if="getCurRole()!='biz_kyry'"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['research:person:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['research:person:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </el-card>

  <div>
    <el-dialog
      :title="title"
      v-model="open"
      width="80%"
      align-center
      :before-close="cancel"
      :close-on-click-modal="false"
      :show-close="false"
      :destroy-on-close="false && true"
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>

      <div class="dialog-content">
        <el-form
          ref="personRef"
          :model="form"
          :rules="rules"
          label-width="150px"
          :disabled="title=='机构人员查看'"
        >
          <el-card class="w-full mt-[10px]">
            <CardHead> 基本信息 </CardHead>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="人员类型" prop="typeId">
                  <el-radio-group v-model="form.typeId">
                    <el-radio
                      v-for="dict in cfg_category_jgrylx"
                      :key="dict.value"
                      :value="dict.value"
                      @change="handleChangeTypeId"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="11"> </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="姓名" prop="name">
                  <el-select
                        v-model="form.name"
                        placeholder="请输入负责人"
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="remoteMethod"
                        :loading="loading1"
                        @change="handleChangeName"
                        v-if="form.typeId==='in'"
                    >
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                            <template #default>  
                                {{ item.label }}（{{item.account}}，{{ item.unitName}}）
                            </template>  
                        </el-option>
                    </el-select>
                    <el-input v-model="form.name" placeholder="请输入姓名" v-else/>
                </el-form-item>
              </el-col>

              <el-col :span="11">
                <el-form-item label="所属单位" prop="unitName">
                  <el-input
                    v-model="form.unitName"
                    placeholder="请输入所属单位"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="性别" prop="sexId">
                  <el-radio-group v-model="form.sexId">
                    <el-radio
                      v-for="dict in cfg_category_xb"
                      :key="dict.value"
                      :value="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker
                    clearable
                    v-model="form.birthday"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择出生日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="学历" prop="eduLevelId" style="align-items: center;">
                  <el-radio-group v-model="form.eduLevelId">
                    <el-radio
                      v-for="dict in cfg_category_xl"
                      :key="dict.value"
                      :value="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="职称" prop="titleId">
                  <el-select v-model="form.titleId" placeholder="请选择职称">
                    <el-option
                      v-for="dict in cfg_category_zc"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="入职时间" prop="hireDate">
                  <el-date-picker
                    clearable
                    v-model="form.hireDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择入职时间"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="离职时间" prop="termDate">
                  <el-date-picker
                    clearable
                    v-model="form.termDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择离职时间"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="w-full mt-[10px]">
            <CardHead> 科技部统计信息 </CardHead>
            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="在职情况" prop="dutyStatus">
                  <el-radio-group v-model="form.dutyStatus">
                    <el-radio
                      v-for="dict in cfg_category_zzzt"
                      :key="dict.value"
                      :value="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="岗位类型" prop="jobType">
                  <el-radio-group v-model="form.jobType">
                    <el-radio
                      v-for="dict in cfg_category_gwlx"
                      :key="dict.value"
                      :value="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="岗位性质" prop="jobKind">
                  <el-radio-group v-model="form.jobKind">
                    <el-radio
                      v-for="dict in cfg_category_gwxz"
                      :key="dict.value"
                      :value="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="是否实验技术人员" prop="isExperTech">
                  <el-radio-group v-model="form.isExperTech">
                    <el-radio
                      v-for="dict in yes_no"
                      :key="dict.value"
                      :value="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="荣誉称号" prop="honorTitleId">
                  <el-checkbox-group v-model="form.honorTitleIdArr">
                    <el-checkbox
                      v-for="dict in cfg_category_rych"
                      :key="dict.value"
                      :value="dict.value"
                    >
                      {{ dict.label }}
                    </el-checkbox>
                  </el-checkbox-group> 
                </el-form-item>
              </el-col>
              <el-col :span="11"> </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="所属资源类型" prop="resourceType">
                  <el-select
                    v-model="form.resourceType"
                    placeholder="请选择所属资源类型"
                  >
                    <el-option
                      v-for="dict in cfg_category_sszylx"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="工作内容" prop="jobContent">
                  <el-select
                    v-model="form.jobContent"
                    placeholder="请选择工作内容"
                  >
                    <el-option
                      v-for="dict in cfg_category_jgrygznr"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="参与平台工作情况" prop="prtpUnit">
                  <el-select
                    v-model="form.prtpUnit"
                    placeholder="请选择参与平台工作情况"
                  >
                    <el-option
                      v-for="dict in cfg_category_cyptgzqk"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="主要学科领域" prop="subjectField">
                  <el-input
                    v-model="form.subjectField"
                    placeholder="请输入主要学科领域"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="save" v-if="title!='机构人员查看'">保存</el-button>
            <el-button @click="cancel">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ResearchPerson">
import cloneDeep from 'lodash/cloneDeep';  
import { back, getKyryByName, getOverPastYearOptions, getCategoryData, getCurRole } from "@/api/research/unit";
import { listPerson, getDutyStatusCount, getPerson,  delPerson,  addPerson,  updatePerson } from "@/api/research/person";

import CardHead from "../components/CardHead.vue";

const { proxy } = getCurrentInstance();
const { yes_no } = proxy.useDict("yes_no");

const personList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const dutyStatusCount = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    researchUnitId: proxy.$route.query.researchUnitId,
    typeId: null,
    name: null,
    unitName: null,
    eduLevelId: null,
    dutyStatus: "",
    jobType: null,
  },
  rules: {
    typeId: [
      { required: true, message: "人员类型不能为空", trigger: "change" },
    ],
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    sexId: [{ required: true, message: "性别不能为空", trigger: "change" }],
    eduLevelId: [
      { required: true, message: "学历不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const saved = ref(null);

const cfg_category_jgrylx = ref([]);
const cfg_category_zzzt = ref([]);
const cfg_category_xl = ref([]);
const cfg_category_gwlx = ref([]);
const cfg_category_zc = ref([]);

const cfg_category_xb = ref([]);
const cfg_category_gwxz = ref([]);
const cfg_category_rych = ref([]);
const cfg_category_sszylx = ref([]);
const cfg_category_jgrygznr = ref([]);
const cfg_category_cyptgzqk = ref([]);

const options = ref([])
const loading1 = ref(false)
const remoteMethod = (query) => {
  if (query) {
    loading1.value = true
    getKyryByName(query).then(res => {
        res.data.map(item => {item.value = item.id; item.label = item.name;});
        options.value = res.data;
        loading1.value = false
    })
  } else {
    options.value = []
  }
}

onMounted(() => {
  getCategoryData(cfg_category_jgrylx, { bizName: "机构人员类型" });
  getCategoryData(cfg_category_zzzt, { bizName: "在职状态" });
  getCategoryData(cfg_category_xl, { bizName: "学历" }, false, ()=>cfg_category_xl.value.sort((a,b)=>{return parseInt(a.value)-parseInt(b.value)}));
  getCategoryData(cfg_category_gwlx, { bizName: "岗位类型" });
  getCategoryData(cfg_category_zc, { bizName: "所有职称" }, true);  //职称单选/职称/所有职称

  getCategoryData(cfg_category_xb, { bizName: "人员-性别(男女)"}, false, ()=>cfg_category_xb.value.sort((a,b)=>{return parseInt(b.value)-parseInt(a.value)}));
  getCategoryData(cfg_category_gwxz, { bizName: "岗位性质" });
  getCategoryData(cfg_category_rych, { bizName: "荣誉称号" });
  getCategoryData(cfg_category_sszylx, { bizName: "所属资源类型" }, true);
  getCategoryData(cfg_category_jgrygznr, { bizName: "机构人员工作内容" }, true);
  getCategoryData(cfg_category_cyptgzqk, { bizName: "参与平台工作情况" }, true);
});

function getList() {
  loading.value = true;
  listPerson(queryParams.value).then((response) => {
    personList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    saved.value = cloneDeep(queryParams.value);
  });

  getDutyStatusCount(queryParams.value).then(response => {
    dutyStatusCount.value = response.data;
    dutyStatusCount.value.all = Object.values(dutyStatusCount.value).reduce((sum,value)=>{return sum+value["dutyStatusCount"]},0);
  });
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    researchUnitId: proxy.$route.query.researchUnitId,
    personId: null,
    typeId: 'in',
    name: null,
    unitName: null,
    sexId: null,
    birthday: null,
    eduLevelId: null,
    titleId: null,
    dutyStatus: null,
    jobType: null,
    jobKind: null,
    isExperTech: null,
    honorTitleId: null,
    resourceType: null,
    subjectField: null,
    jobContent: null,
    prtpUnit: null,
    hireDate: null,
    termDate: null,
    createUserId: null,
    lastEditUserId: null,
    createDate: null,
    lastEditDate: null,
    createUserName: null,
    lastEditUserName: null,
    processInstanceId: null,

    honorTitleIdArr: [],
  };
  proxy.resetForm("personRef");
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.researchUnitId = proxy.$route.query.researchUnitId,
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleChangeTypeId(params) {
    // if (form.value.typeId === 'in') {//切换到校内
        
    // } else if (form.value.subjectClassId === 'out') {//切换到校外
        
    // }
    form.value.name = "";
    form.value.personId = "";
    form.value.unitName = "";
    form.value.birthday = "";
}

function handleChangeName(params) {
    const selectedOption = options.value.find(option => option.id === params);
    form.value.name = selectedOption ? selectedOption.name : '';
    form.value.personId = selectedOption ? selectedOption.id : '';
    form.value.unitName = selectedOption ? selectedOption.unitName : '';
    form.value.birthday = selectedOption ? selectedOption.birthday : '';
    form.value.sexId = selectedOption ? selectedOption.sexId : '';
    form.value.eduLevelId = selectedOption ? selectedOption.eduLevelId : '';
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = "机构人员新增";
}

function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPerson(_id).then((response) => {
    form.value = response.data;
    form.value.honorTitleIdArr = form.value.honorTitleId ? form.value.honorTitleId.split(",") : [];
    open.value = true;
    title.value = "机构人员编辑";
  });
}

function handleView(row) {
  const _id = row.id || ids.value;
  getPerson(_id).then((response) => {
    form.value = response.data;
    form.value.honorTitleIdArr = form.value.honorTitleId ? form.value.honorTitleId.split(",") : [];
    open.value = true;
    title.value = "机构人员查看";
  });
}

function save() {
  proxy.$refs["personRef"].validate((valid) => {
    if (valid) {
      form.value.honorTitleId = form.value.honorTitleIdArr.join(",");
      if (form.value.id != null) {
        updatePerson(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPerson(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('您确定要删除吗?')
    .then(function () {
      return delPerson(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

onActivated(()=>{if (queryParams.value.researchUnitId===proxy.$route.query.researchUnitId) {if(saved.value){queryParams.value=cloneDeep(saved.value);getList();}} else {reset();resetQuery();}})
getList();
</script>

<style scoped lang="scss">
@import url("@/views/research/index.scss");
:deep(.el-tabs__header) {
  padding: 0 10px;
  margin-bottom: 0;
  background: #fff;
}

:deep(.el-button--danger.is-disabled *){
    color: var(--el-color-danger-light-5) !important;
    -webkit-text-fill-color: var(--el-color-danger-light-5) !important;
}
</style>
